package com.cn.longdistancebusstation.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.cn.longdistancebusstation.BuildConfig;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.busInfo.BusInfoListActivity;
import com.cn.longdistancebusstation.calendar.CalendarActivity;
//import com.cn.longdistancebusstation.city.MainActivity;
import com.cn.longdistancebusstation.base.BaseFragment;
import com.cn.longdistancebusstation.home.NewsDetailActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.javaBean.ViewPagerBean;
import com.cn.longdistancebusstation.model.ListResult;
import com.cn.longdistancebusstation.model.News;
import com.cn.longdistancebusstation.model.Station;
import com.cn.longdistancebusstation.stationList.StationListActivity;
import com.cn.longdistancebusstation.view.ImageCycleView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//import com.cn.longdistancebusstation.city.MainActivity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2018/1/15.
 */

public class IndexFragment extends BaseFragment implements View.OnClickListener{
    private static final int REQUEST_STATION_LIST = 1;
    private static final int REQUEST_CALENDAR = 2;
    /**
     * 首页视图
     */
    private View mView;
    /*
	 * 图片轮播需要
	 */
    private EditText mDestinationEditText, mOutingDateEditText;
    private Button btn_inquiry;
    private String mdestinationString;
    private ImageCycleView mImageCycleView;
    private ArrayList<News> mBannerList = new ArrayList<>();
    private ArrayList<String> filePathList;
    private ImageView select_time;

    //目的地站点
    Station mDesStation;
    //出行日期，默认当天
    String mOutingDate;
    private RelativeLayout mRelativeLayout;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        mView=inflater.inflate(R.layout.activity_index,null);
        mDestinationEditText =(EditText)mView.findViewById(R.id.destination);
        mDestinationEditText.setOnClickListener(this);
        mOutingDateEditText =(EditText)mView.findViewById(R.id.kalendar);
        mOutingDateEditText.setOnClickListener(this);
        mRelativeLayout=(RelativeLayout)mView.findViewById(R.id.index_banner1);
        //
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        mOutingDate = dateFormat.format(date);
        mOutingDateEditText.setText(dateFormat.format(date)+" (今天)");
        //
        select_time=(ImageView)mView.findViewById(R.id.select_time);
        select_time.setOnClickListener(this);
        btn_inquiry=(Button)mView.findViewById(R.id.btn_inquiry);
        btn_inquiry.setOnClickListener(this);
        mImageCycleView =(ImageCycleView)mView.findViewById(R.id.index_lunbo);
        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("data",Context.MODE_PRIVATE);
        mdestinationString=sharedPreferences.getString("destination","");
//        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));


        imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.mipmap.pre_loading)//设置图片URL为空或是错误的时候显示图片
                .showImageOnFail(R.mipmap.pre_loading)//image加载失败或解码过程错误显示的图片
                .resetViewBeforeLoading(true)//设置下载的图片下载前是否重置，复位
                .cacheInMemory(true)//设置下载图片是否缓存到内存
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片解码类型
                .displayer(new FadeInBitmapDisplayer(300))//设置用户加载图片的task(这里是渐现)
                .build();

        //imageLoader.displayImage(urlString, img_loadView,options);
        getViewPagerResponseData();
        return mView;
    }

    private void getViewPagerResponseData(){
        Retrofit retrofit = new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService = retrofit.create(HttpService.class);
        Call<ListResult<News>> call = httpService.getNews();
        call.enqueue(new Callback<ListResult<News>>() {

            @Override
            public void onResponse(Call<ListResult<News>> call, Response<ListResult<News>> response) {
                ListResult result = response.body();
                Gson gson = new Gson();
                String strBody = gson.toJson(result.getBody().getData());
                Log.d("数据",strBody);
                Type listType = new TypeToken<List<News>>() {
                }.getType();
                mBannerList = gson.fromJson(strBody, listType);
                filePathList = new ArrayList<>();
                for (int i = 0; i < mBannerList.size(); i++) {
                    filePathList.add(BuildConfig.SERVER_URL+mBannerList.get(i).getFile().getFilePath());
                }
                mImageCycleView.setImageResources(filePathList, mAdCycleViewListener);

            }

            @Override
            public void onFailure(Call<ListResult<News>> call, Throwable t) {

            }
        });
    }
    private ImageCycleView.ImageCycleViewListener mAdCycleViewListener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void displayImage(String imageURL, ImageView imageView) {
//            ImageLoader.getInstance().displayImage(imageURL, imageView);
            imageLoader.displayImage(imageURL, imageView,options);

        }


        @Override
        public void onImageClick(int postion, View imageView) {
            News news = mBannerList.get(postion);
            Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
            intent.putExtra("content", news.getContent());
            startActivity(intent);
        }

    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.destination:
                mDestinationEditText.clearFocus();
                destination();
                break;
            case R.id.kalendar:
                mDestinationEditText.clearFocus();
                kalendar();
                break;
            case R.id.btn_inquiry:
                inquiry();
                break;
        }

    }

    /*
    * 查询车次列表
    * */
    private void inquiry() {
        if (mDesStation == null){
            Toast.makeText(getActivity(),"请选择目的站点",Toast.LENGTH_SHORT).show();
        }else{
            Intent intent = new Intent(getActivity(), BusInfoListActivity.class);
            intent.putExtra("station", mDesStation);
            intent.putExtra("date", mOutingDate);
            startActivity(intent);
        }

    }

    /*
    * 目的地站点列表
    * */
    private void destination() {
        Intent intent = new Intent(getActivity(), StationListActivity.class);
        startActivityForResult(intent , REQUEST_STATION_LIST);
    }
    private void kalendar(){
        Intent intent=new Intent(getActivity(), CalendarActivity.class);
        intent.putExtra("outingDate", mOutingDate);
        startActivityForResult(intent,REQUEST_CALENDAR);
    }
    //查询目的地
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null) return;
        if(requestCode == REQUEST_STATION_LIST){
            if(resultCode == RESULT_OK){
                mDesStation = (Station) data.getSerializableExtra("station");
                mDestinationEditText.setText(mDesStation.getStationName());
            }
        }
        else if(requestCode == REQUEST_CALENDAR){
            mOutingDate = data.getStringExtra("outingDate");
            if(mOutingDate != null){
                Date todayDate = new Date();
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String strToday = dateFormat.format(todayDate);
                if(mOutingDate.equals(strToday)){
                    mOutingDateEditText.setText(mOutingDate + " (今天)");
                }
                else{
                    mOutingDateEditText.setText(mOutingDate);
                }
            }
        }
    }

}
